#include <iostream>
#include <pthread.h>
#include <string>
#include <vector>
#include <unistd.h>
#include "Mutex.hpp"
#define N 4
int ticket = 1000;
using namespace std;
class ThreadName
{
public:
    ThreadName(int name, pthread_mutex_t *lock)
    {
        _threadName += "thread:" + to_string(name);
        _lock = lock;
    }
    const string &getName()
    {
        return _threadName;
    }
    pthread_mutex_t *&getMutex()
    {
        return _lock;
    }

private:
    string _threadName;
    pthread_mutex_t *_lock;
};
void *handler(void *arg)
{
    ThreadName *ptr = static_cast<ThreadName *>(arg); // 强转为ThreadName*
    while (true)
    {
        // 临界区————————————————————————————————————————————————————；
        // 加锁；
        //  pthread_mutex_lock(ptr->getMutex());
        {
            Mutex lock(ptr->getMutex());
            if (ticket > 0)
            {
                printf("%s-get ticket:%d\n", ptr->getName().c_str(), ticket);
                ticket--;
                // pthread_mutex_unlock(ptr->getMutex());
            }
            else
            {
                // pthread_mutex_unlock(ptr->getMutex());
                break;
            }
        }

        // 临界区————————————————————————————————————————————————————————；
        usleep(10);
    }
    return nullptr;
}
int main()
{
    vector<pthread_t> vt;
    vector<ThreadName *> vn;
    pthread_mutex_t lock;
    pthread_mutex_init(&lock, nullptr); // 初始化锁；
    for (int i = 0; i < N; i++)
    {
        pthread_t tid;
        ThreadName *ptr = new ThreadName(i + 1, &lock);
        pthread_create(&tid, nullptr, handler, ptr);
        vn.push_back(ptr);
        vt.push_back(tid);
    }
    sleep(1);
    for (auto e : vt)
    {
        pthread_join(e, nullptr);
    }
    for (auto e : vn)
    {
        delete e;
    }
    pthread_mutex_destroy(&lock); // 销毁锁；
    return 0;
}